import email.mime.image

import flask

from info.moudels.passport import passport_blu
from flask import request,abort,current_app,make_response
from info.utils.captcha.captcha import captcha
from info import redis_store,constants
from email.mime import image


@passport_blu.route('/image_code')
def get_image_code():
    """
    1.获取参数
    2.校验参数
    3.生成验证码
    4.把随机的字符串和生成的文本验证码以k：v的形式保存在redis中
    5.把图片验证码返回浏览器
    :return:
    """
    # 1.获取参数
    image_code_id = request.args.get("imageCodeId")
    # 2.校验参数
    if not image_code_id:
        abort(404)
    # 3.生成验证码
    _,text,image = captcha.generate_captcha()
    # 4.把随机的字符串和生成的文本验证码以k：v的形式保存在redis中
    try:
        redis_store.setex("ImageCodeId_"+image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)
        abort(502)
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response

